package com.gaojinqi.base.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * http request response 工具类
 *
 * @author gaojinqi
 * @version 1.0
 * @since 2020年05月14日
 */
@Slf4j
public class RequestResponseUtil {

    /**
     * 取request中的已经被防止XSS，SQL注入过滤过的key value数据封装到map 返回
     */
    public static Map<String, String> getRequestParameters(ServletRequest request) {
        Map<String, String> dataMap = new HashMap<>(16);
        Enumeration<String> enums = request.getParameterNames();
        while (enums.hasMoreElements()) {
            String paraName = enums.nextElement();
            String paraValue = RequestResponseUtil.getRequest(request).getParameter(paraName);
            if (null != paraValue && !"".equals(paraValue)) {
                dataMap.put(paraName, paraValue);
            }
        }
        return dataMap;
    }

    /**
     * 读取request 已经被防止XSS，SQL注入过滤过的 请求参数key 对应的value
     */
    public static String getParameter(ServletRequest request, String key) {
        return RequestResponseUtil.getRequest(request).getParameter(key);
    }

    /**
     * 读取request 已经被防止XSS，SQL注入过滤过的 请求头key 对应的value
     */
    public static String getHeader(ServletRequest request, String key) {
        return RequestResponseUtil.getRequest(request).getHeader(key);
    }

    /**
     * 取request头中的已经被防止XSS，SQL注入过滤过的 key value数据封装到map 返回
     */
    public static Map<String, String> getRequestHeaders(ServletRequest request) {
        Map<String, String> headerMap = new HashMap<>(16);
        Enumeration<String> enums = RequestResponseUtil.getRequest(request).getHeaderNames();
        while (enums.hasMoreElements()) {
            String name = enums.nextElement();
            String value = RequestResponseUtil.getRequest(request).getHeader(name);
            if (null != value && !"".equals(value)) {
                headerMap.put(name, value);
            }
        }
        return headerMap;
    }

    /**
     * 获取指定key的cookie值
     */
    public static String getCookie(ServletRequest request, String key) {
        Cookie[] cookies = RequestResponseUtil.getRequest(request).getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                String value = cookie.getValue();
                if (Objects.equals(key, name)) {
                    return value;
                }
            }
        }
        return null;
    }

    /**
     * 获取所有cookie
     */
    public static Map<String, String> getCookies(ServletRequest request) {
        Map<String, String> cookieMap = new HashMap<>(16);
        Cookie[] cookies = RequestResponseUtil.getRequest(request).getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                String value = cookie.getValue();
                if (name != null && name.length() > 0) {
                    cookieMap.put(name, value);
                }
            }
        }
        return cookieMap;
    }

    /**
     * 设置响应头
     */
    public static void setHeader(ServletResponse response, String key, String val) {
        RequestResponseUtil.getResponse(response).setHeader(key, val);
    }


    /**
     * 设置Cookie
     */
    public static void setCookie(ServletResponse response, String key, String val) {
        Cookie cookie = new Cookie(key, val);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        RequestResponseUtil.getResponse(response).addCookie(cookie);
    }

    /**
     * 封装response  统一json返回
     */
    public static void responseWrite(String outStr, ServletResponse response) {
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter printWriter;
        try {
            printWriter = RequestResponseUtil.getResponse(response).getWriter();
            printWriter.write(outStr);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 包装 request，可加入防止XSS，SQL注入过滤功能
     */
    public static HttpServletRequest getRequest(ServletRequest request) {
        return ((HttpServletRequest) request);
    }


    /**
     * 包装 response
     */
    public static HttpServletResponse getResponse(ServletResponse response) {
        return ((HttpServletResponse) response);
    }

}
